package UDP回显服务器;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPService {
    private DatagramSocket socket=null;
    //构造方法，指定服务器的端口号
    public UDPService(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器已启动");
        while (true){
            //读取客户端的请求
            DatagramPacket requestPacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);//如果没收到请求就阻塞等待，收到了请求就包装给request
            //解析请求
            String request=new String(requestPacket.getData(),0, requestPacket.getLength());//由于getData得到的是整个数组，数组不一定为满，所以要进行长度的限制
            //处理请求
            String response=process(request);
            //构造返回的响应包
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            //发送响应给客户端
            socket.send(responsePacket);
            System.out.printf("[%s:%d] request=%s; response=%s\n", requestPacket.getAddress().toString(), requestPacket.getPort(),
                    request, response);
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UDPService service=new UDPService(8000);
        service.start();
    }
}

